#include "formcam.h"
#include "ui_formcam.h"
#include "jcode.h"
#include <QCloseEvent>
#include <QDir>
#include <QFile>

#include <QtGui>
#include <QScrollBar>
#include <QPalette>
#include <QDate>
#include <QInputDialog>
#include <QMessageBox>

#include <QDebug>
#include <QSplitter>
#include <QHttpMultiPart>



FormCam::FormCam(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::FormCam)
{
    ui->setupUi(this);
    //this->show();
    this->setWindowTitle("启用摄像头拍照");
    ui->cmdUpfile->setVisible(false);
    ui->cmbRotate->clear();
    ui->cmbRotate->addItem("0");
    ui->cmbRotate->addItem("90");
    ui->cmbRotate->addItem("180");
    ui->cmbRotate->addItem("270");
    ui->cmbRotate->setCurrentText("270");
    ui->label->setScaledContents(true); //自适应内容大小,用来展示截图
    ui->label_hb->setScaledContents(true); //自适应内容大小,用来展示截图
    mCamera = NULL;
    //摄像头显示再控件中
    mViewfinder = new QCameraViewfinder(ui->viewfinder);
    mViewfinder->resize(ui->viewfinder->size());
    mViewfinder->setAspectRatioMode(Qt::KeepAspectRatio);//设置全视角显示
    ListCamera();
    //打开默认摄像头
    QString str=ui->cmbCAM->currentText().trimmed();
    openCamera(str);

    QDir *folder = new QDir;
    QString aFile = QDir::currentPath();
    QString pdfPath =QString("%1/pdftmp").arg(aFile);
    //folder->mkdir(QString("%1/tmp").arg(aFile));
    folder->mkdir(pdfPath);
    //判断PDF临时图片文件是否存在， 存在就直接删除
    for (int i=1;i<=9999;i++){
        QString JpgFile =QString("%1/%2.jpg").arg(pdfPath).arg(QString("%1").arg(i,4,10,QChar('0')));
        QFile PICfile(JpgFile);
        if (PICfile.exists()){
            PICfile.remove();
        }
    }
    JpgCount=0;
    ui->treeWidget->clear();
    ui->treeWidget->setHeaderLabels(QStringList() << "序号" << "文件名" );
    ui->treeWidget->setColumnWidth(0,80);
    //ui->treeWidget->header()->setSectionResizeMode(QHeaderView::ResizeToContents); //QTreeWidget设置根据内容自适应宽度
}
void FormCam::closeEvent (QCloseEvent *event)
{
    //捕捉窗口关闭事件，自动关闭摄像头
    if(mCamera != NULL){
        mCamera->stop();
    }
    event->accept();
}

FormCam::~FormCam()
{
    delete ui;
}
void FormCam::ListCamera()
{
    QList<QCameraInfo> cameras = QCameraInfo::availableCameras();
    foreach (const QCameraInfo &cameraInfo, cameras){
         ui->cmbCAM->addItem(cameraInfo.description());
    }
}

void FormCam::openCamera(QString description)
{
    if(mCamera != NULL){
        mCamera->stop();
    }

    if(description.isEmpty()){
        QCameraInfo info = QCameraInfo::defaultCamera(); //默认摄像头
        mCamera = new QCamera(info,this);
    }else{
        QList<QCameraInfo> cameras = QCameraInfo::availableCameras();
        foreach (const QCameraInfo &cameraInfo, cameras){
            if(cameraInfo.description() == description){
                mCamera = new QCamera(cameraInfo,this);
                break;
            }
        }
    }
    mCamera->setCaptureMode(QCamera::CaptureVideo);
    connect(mCamera, static_cast<void(QCamera::*)(QCamera::Error)>(&QCamera::error),
         [=](QCamera::Error value){ qDebug()<<value;});

    mCamera->start();

    //列出摄像头的最高分辨率 设定之
    int CamWidth=0;
    int CamHeight=0;
    QList<QSize> sizes = mCamera->supportedViewfinderResolutions();
        //qDebug() << "viewfinderResolutions sizes.len = " << sizes.length();
        ui->cmbCAM_SIZE->clear();
        foreach (QSize size, sizes) {
            ui->cmbCAM_SIZE->addItem(QString("%1 X %2").arg(size.width()).arg(size.height()));
            //qDebug() << "Resolutions size = " << size;
            if (CamWidth<size.width()){
                CamWidth=size.width();
            }
            if (CamHeight<size.height()){
                CamHeight=size.height();
            }
        }
        //为了保持精度 始终以最高分辨率显示摄像头
        mCamera->stop();
        QCameraViewfinderSettings set;
        set.setResolution(CamWidth, CamHeight); //设置摄像头分辨率

        mCamera->setViewfinderSettings(set);
        //设置摄像头取景器
        mCamera->setViewfinder(mViewfinder);
        mCamera->imageProcessing()->setBrightness(ui->s_LD->value()/100);
        mCamera->imageProcessing()->setContrast(ui->s_DB->value()/100);


        //绑定截图对象
        mImageCapture = new QCameraImageCapture(mCamera);
        //connect(mImageCapture,SIGNAL(imageCaptured(int,QImage)),SLOT(onImageCaptured(int,QImage)));
        //bindRecoder(mCamera);
        //开启摄像头
        mCamera->start();
    QObject::connect(ui->cmdCap,SIGNAL(clicked()),this,SLOT(ShowTheCapture()));
    //QObject::connect(ui->cmdSavePic,SIGNAL(clicked()),this,SLOT(SavePicture()));
    QObject::connect(mImageCapture, SIGNAL(imageCaptured(int,QImage)), this, SLOT(displayImage(int,QImage)));


}

/*
@brief          设置录制格式
@param  camera  摄像头对象
@return
windows 下测试无效，其他解决方案 用QtMEL 详情 http://kibsoft.ru/
*/
void FormCam::bindRecoder(QCamera *camera)
{
    mMediaRecorder = new QMediaRecorder(camera,this);
    connect(mMediaRecorder, static_cast<void(QMediaRecorder::*)(QMediaRecorder::Error)>(&QMediaRecorder::error),
        [=](QMediaRecorder::Error error){ qDebug()<<error;});
    connect(mMediaRecorder,&QMediaRecorder::statusChanged,[=](QMediaRecorder::Status status){qDebug()<<status;});

    //设置音频编码格式
    QAudioEncoderSettings audioSettings;
    audioSettings.setCodec("audio/amr");
    audioSettings.setQuality(QMultimedia::HighQuality);
    //mMediaRecorder->setAudioSettings(audioSettings);

    QVideoEncoderSettings settings = mMediaRecorder->videoSettings();

    settings.setResolution(640,480);
    settings.setQuality(QMultimedia::VeryHighQuality);
    settings.setFrameRate(30.0);
    settings.setCodec("video/mp4");

    mMediaRecorder->setVideoSettings(settings);
    mMediaRecorder->setOutputLocation(QUrl(qApp->applicationDirPath() + "/xzp.mp4"));
}

void FormCam::ShowTheCapture()
{

    QString aFile = QDir::currentPath();
    mImageCapture->capture(QString("%1/tmp/tmp.jpg").arg(aFile));
}
void FormCam::displayImage(int ,QImage image)
{
    image=image.convertToFormat(QImage::Format_RGB888);
    ui->label->setPixmap(QPixmap::fromImage(image));
    //QImage::Format format =  image.format();
    //qDebug() << (int)format;
    ui->label_hb->setPixmap(QPixmap::fromImage(JCode::PIC_NoBlack(image,ui->cmbRotate->currentText().toInt())));
    ui->label_hb->show();
    JpgCount++;
    QString aFile = QDir::currentPath();
    QString pdfPath =QString("%1/pdftmp").arg(aFile);
    QString JpgFile =QString("%1/%2.jpg").arg(pdfPath).arg(QString("%1").arg(JpgCount,4,10,QChar('0')));
    const QPixmap *pixmap = ui->label_hb->pixmap();
    if(pixmap)
    {
        pixmap->save(JpgFile);
        QStringList child;
        child.clear();
        child << QString("%1").arg(JpgCount,4,10,QChar('0'));
        child << JpgFile;
        QTreeWidgetItem * citem =new QTreeWidgetItem(child);

        ui->treeWidget->addTopLevelItem(citem);
    }
}
void FormCam::SavePicture()
{
    const QPixmap *pixmap = ui->label_hb->pixmap();
    if(pixmap)
    {
        QString aFile = QDir::currentPath();
        pixmap->save(QString("%1/pdftmp/tmp.jpg").arg(aFile));
        qDebug()<<"保存上了"<<endl;
    }

}

void FormCam::on_cmdStart_clicked()
{
    QString str=ui->cmbCAM->currentText().trimmed();
    openCamera(str);
}

void FormCam::on_cmdStop_clicked()
{
    if(mCamera != NULL){
        mCamera->stop();
    }
}

void FormCam::on_cmbCAM_currentIndexChanged(const QString &arg1)
{
    QString str=arg1;
    openCamera(str);
}

void FormCam::on_cmdSavePdf_clicked()
{
    QString fileName="";
    fileName= QCoreApplication::applicationDirPath();
    fileName +="/tmp.pdf";
    QFile pdfFile(fileName);
    pdfFile.open(QIODevice::WriteOnly);                 // 打开要写入的pdf文件
    QPdfWriter* pPdfWriter = new QPdfWriter(&pdfFile);  // 创建pdf写入器
    pPdfWriter->setPageSize(QPagedPaintDevice::A4);     // 设置纸张为A4
    pPdfWriter->setResolution(300);                     // 设置纸张的分辨率为300,因此其像素为3508X2479
                                                        //3508/3*2=2339 2479/3*2=1653  2560*1920
    pPdfWriter->setTitle("这里是表头");
    int iMargin = 50;                   // 页边距
    pPdfWriter->setPageMargins(QMarginsF(iMargin, iMargin, iMargin, iMargin)); //上下左右页边距
    QPainter* pPdfPainter = new QPainter(pPdfWriter);   // qt绘制工具
    QTreeWidgetItemIterator it(ui->treeWidget);
    int PageNO=0;
        while (*it) {
             //(*it)->text(0);

            if (PageNO>0){
                pPdfWriter->newPage();//开启新页
            }
            //加载图片
            QString str=(*it)->text(1);
            QPixmap image1;
            image1.load(str);
            //自动放大或者缩小到满屏 并且图片居中
            int w=0;
            int h=0;
            int x=0;
            int y=0;
            w=pPdfWriter->width();
            h=image1.height()*pPdfWriter->width()/image1.width();
            x=0;
            y=(pPdfWriter->height()-h)/2;
            if (h>pPdfWriter->height()){
                h=pPdfWriter->height();
                w=image1.width()*pPdfWriter->height()/image1.height();
                x=(pPdfWriter->width()-w)/2;
                y=0;
            }
            pPdfPainter->drawPixmap(x,y,w,h,image1);
            PageNO++;
            ++it;
        }


    delete pPdfPainter;
    delete pPdfWriter;
    pdfFile.close();
    emit sendData(fileName);
    this->close();
    //QDesktopServices::openUrl(QUrl::fromLocalFile(fileName)); //根据你电脑默认的PDF打开方式 直接打开PDF文件 需要安装阅读器

}

void FormCam::on_s_DB_valueChanged(int value)
{
    int i=0;
    i=value;
    i++;
    QString str=ui->cmbCAM->currentText().trimmed();
    openCamera(str);
}

void FormCam::on_s_LD_valueChanged(int value)
{
    int i=0;
    i=value;
    i++;
    QString str=ui->cmbCAM->currentText().trimmed();
    openCamera(str);
}

void FormCam::on_cmdClearList_clicked()
{
    QDir *folder = new QDir;
    QString aFile = QDir::currentPath();
    QString pdfPath =QString("%1/pdftmp").arg(aFile);
    //folder->mkdir(QString("%1//tmp").arg(aFile));
    folder->mkdir(pdfPath);
    //判断PDF临时图片文件是否存在， 存在就直接删除
    for (int i=1;i<=9999;i++){
        QString JpgFile =QString("%1//%2.jpg").arg(pdfPath).arg(QString("%1").arg(i,4,10,QChar('0')));
        QFile PICfile(JpgFile);
        if (PICfile.exists()){
            PICfile.remove();
        }
    }
    JpgCount=0;
    ui->treeWidget->clear();
    ui->treeWidget->setHeaderLabels(QStringList() << "序号" << "文件名" );
    ui->treeWidget->setColumnWidth(0,80);
}

void FormCam::on_cmdUP_clicked()
{
    int rowNo=ui->treeWidget->currentIndex().row();
    if (rowNo>0){
        QString S1=ui->treeWidget->topLevelItem(rowNo)->text(0);
        QString S2=ui->treeWidget->topLevelItem(rowNo)->text(1);
        QString S3=ui->treeWidget->topLevelItem(rowNo-1)->text(0);
        QString S4=ui->treeWidget->topLevelItem(rowNo-1)->text(1);
        ui->treeWidget->topLevelItem(rowNo)->setText(0,S3);
        ui->treeWidget->topLevelItem(rowNo)->setText(1,S4);
        ui->treeWidget->topLevelItem(rowNo-1)->setText(0,S1);
        ui->treeWidget->topLevelItem(rowNo-1)->setText(1,S2);
        QTreeWidgetItem * currentItem = ui->treeWidget->topLevelItem(rowNo-1);
        ui->treeWidget->setCurrentItem(currentItem);
    }

}

void FormCam::on_cmdDel_clicked()
{
    QTreeWidgetItem * currentItem = ui->treeWidget->currentItem();

        if(currentItem==NULL)
        {
            return;
        }
        QString selectNo="";
        selectNo=currentItem->text(0);
        QMessageBox message(QMessageBox::Warning,"请确认",QString("确认删除选中[%1]的记录吗?").arg(selectNo),QMessageBox::Yes|QMessageBox::No,NULL);
            if (message.exec()==QMessageBox::Yes)
            {
                //如果没有父节点就直接删除
                if(currentItem->parent()==NULL)
                {
                    delete ui->treeWidget->takeTopLevelItem(ui->treeWidget->currentIndex().row());
                }
                else
                {
                    //如果有父节点就要用父节点的takeChild删除节点
                    delete currentItem->parent()->takeChild(ui->treeWidget->currentIndex().row());
                }

            }

    }



void FormCam::on_cmdDown_clicked()
{
    int rowNo=ui->treeWidget->currentIndex().row();
    QTreeWidgetItemIterator it(ui->treeWidget);
    int RowCount=0;
        while (*it) {
            RowCount++;
            ++it;
        }
    if (rowNo<RowCount-1)
    {
        QString S1=ui->treeWidget->topLevelItem(rowNo)->text(0);
        QString S2=ui->treeWidget->topLevelItem(rowNo)->text(1);
        QString S3=ui->treeWidget->topLevelItem(rowNo+1)->text(0);
        QString S4=ui->treeWidget->topLevelItem(rowNo+1)->text(1);
        ui->treeWidget->topLevelItem(rowNo)->setText(0,S3);
        ui->treeWidget->topLevelItem(rowNo)->setText(1,S4);
        ui->treeWidget->topLevelItem(rowNo+1)->setText(0,S1);
        ui->treeWidget->topLevelItem(rowNo+1)->setText(1,S2);
        QTreeWidgetItem * currentItem = ui->treeWidget->topLevelItem(rowNo+1);
        ui->treeWidget->setCurrentItem(currentItem);
    }
}



void FormCam::on_treeWidget_itemClicked(QTreeWidgetItem *item, int column)
{
    int i=column;
    i++;
    QString str=item->text(1);
    QPixmap image1;
    image1.load(str);
    ui->label_hb->setPixmap(image1);
}
void FormCam::uploadFinished()
{
    // 获取数据
    if (QNetworkReply::NoError == reply->error()){
        QByteArray context = reply->readAll();
        //QTextCodec* pCodec = QTextCodec::codecForName("UTF-8");
        //QString strResult = pCodec->toUnicode(context);//输出返回的文本

        QJsonObject result_obj = QJsonDocument::fromJson(context).object();
        int code = result_obj.value("code").toInt();
        qDebug()<<"code:"<<code<<result_obj;
    }
    else{
        qDebug()<<"error string:"<<reply->errorString();
        reply->deleteLater();
    }
}

void FormCam::on_cmdUpfile_clicked()
{
        QString  url_ ="http://localhost/test/upfile.php";

        QString fileName="";
        fileName= QCoreApplication::applicationDirPath();
        fileName +="/tmp.pdf";
        QString uploadFilename=fileName;//上传路径,可自定义
        QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);

        QHttpPart imagePart;
        QFile *file = new QFile(uploadFilename);
        file->open(QIODevice::ReadOnly);
        imagePart.setBodyDevice(file);
        imagePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("text/html"));//设置上传文件类型
        imagePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"file\"; filename=\"" + file->fileName() + "\""));
        multiPart->append(imagePart);

        QHttpPart dataPart;
        //在body体中设置值，在这里是999
        dataPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"sn\""));
        dataPart.setBody("999");
        multiPart->append(dataPart);

        QUrl url(url_);
        QNetworkRequest request(url);

        QNetworkAccessManager *networkManager= new QNetworkAccessManager;
        reply = networkManager->post(request, multiPart);
        multiPart->setParent(reply);

        //关联槽,上传完成后输出返回信息
        connect(reply,SIGNAL(finished()),this,SLOT(uploadFinished()));

}
